/**
 * 工具类
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var UI = {
                /**
         * tab切换效果
         * @param {String} ulID   tab项的外层ID
         * @param {String} infoID 显示内容项的ID
         * @param {String} cName  选中样式名称
         */
        tab: function (ulID,infoID,cName){
            var lst = document.getElementById(ulID).getElementsByTagName("li");
            for(var i=0; i<lst.length; i++){
                lst[i].index = i+1;
                lst[i].onclick =function(){
                    for(var j=1; j<=lst.length; j++){
                        lst[j-1].className = "";
                        document.getElementById(infoID+j).style.display = "none" ;
                    }
                    this.className = cName;
                    document.getElementById(infoID+this.index).style.display = "block" ; 
                }
            }
        },
        /**
         * 创建loading
         * @param {String} id     loading创建在对应id的dom元素内容
         * @param {String} text   需要修改的文字
         * @param {String} state  判断是否成功/失败，显示对应样式
         */
        loading: function(id, text, state){
            var str = '', 
                text = text ? text : "正在加载...",
                iconCls = 'loading-icon',
                obj = "body",
                loadCls = "loading";
            // 判断是否已经有loading
            var isload = document.getElementById("loading");
            if(isload){
                return;
            }
            if(id){
                obj = "#"+id;
                height = $(obj).height();
                loadCls = "loading-abs";
            }else{
                height = $(window).height();
            }
            if(state){
                iconCls = state === "success"? "loading-success" : "loading-false";
            }
            str += '<div id="loading" class="' + loadCls + '"><div class="loading-con"><div class="loading-img"><i class='+ iconCls +'></i></div>';
            str += '<p>' + text + '</p>';
            str += '</div></div>';
            $(obj).append(str);
            $("#loading").css("top", height/2-62);
            if(state){
                var _this = this;
                setTimeout(function(){
                    _this.removeLoading();
                },3500);
            }
        },
        /**
         * 删除loading
         */
        removeLoading: function(){
            $("#loading").remove();
        },
        //操作成功提示
        showSucTip:function(msg){
            msg = msg || "操作成功";
            this.removeLoading();
            this.loading(null,msg,"success");
        },
        //操作失败提示
        showErrTip:function(msg){
            msg = msg || "操作失败";
            this.removeLoading();
            this.loading(null,msg,"error");
        },
        /**
         * 全选、取消全选
         */
        checkToggle: function (allCheckboxName, checkboxName) {
            var o = document.getElementsByName(allCheckboxName);
            this.checkAll(checkboxName,o[0].checked);
        },
        /**
         * 全选
         */
        checkAll: function (checkboxName,state) {
            var o = document.getElementsByName(checkboxName);
            for (var i = 0, len = o.length; i < len; i++) {
                o[i].checked = state;
            }
        },
        /**
         * 修改tips里小箭头的位置, 指向对应的项
         * @param {Object} obj     点击的标签
         */
        changeTipsArrow: function (obj) {
            var left = $(obj).position().left;
            var width = $(obj).width();
            left = left + width/2;
            $(".tips-arrow").css("margin-left",left);
        },
        /**
         * 初始化控件
         */
        init: function (){
            this.bindEvent();
        },
        /**
         * 绑定事件
         */
        bindEvent: function (){
            $(function(){

                // 下拉框选择
                $(".js-select").on("click",function(e){
                    $(".select").removeClass("select-on"); 
                    //var text = $(this).find(".select-text");
                    $(this).parent().addClass("select-on");
                    e.stopPropagation();
                });

                //点击桌面隐藏弹层
                $(document).click(function(e){
                    $(".select").removeClass("select-on"); 
                });

                //单选开关
                // $(".switch").on("click",function(){
                //     var _this = $(this),
                //         text = $(this).find(".switch-text"),
                //         cls = $(this).attr("class");
                //     if(cls.indexOf("switch-on") > 0){
                //         $(this).removeClass("switch-on").addClass("switch-off");
                //         text.text("关");
                //     }else{
                //         $(this).removeClass("switch-off").addClass("switch-on");
                //         text.text("开");
                //     }
                // });
            });
        },
        /**
         * 绑定开关控件的事件
         * @param {type} el 开关控件id
         * @param {type} callBack 切换状态的回调方法
         * @param {type} context 回调方法上下文对象
         * @returns {undefined}
         */
        initSwitch:function(el,callBack,context){
            $(el).off().bind("click",function(e){
                var $el = $(this);
                var data = {};
                if($el.hasClass("switch-off")){
                    $el.removeClass("switch-off").addClass("switch-on");
                    $el.find(".switch-text").text("开");
                    data = {
                        value:1,
                        text:"开"
                    };
                }else{
                    $el.removeClass("switch-on").addClass("switch-off");
                    $el.find(".switch-text").text("关");
                    data = {
                        value:0,
                        text:"关"
                    }
                }
                if(typeof callBack == "function"){
                    context = context || this;
                    callBack.call(context,data);
                }
            });
        },
        /**
         * 绑定加减计数控件
         * @param {type} el 加减计数控件id
         * @returns {undefined}
         */
        initCount: function(el){
            var el = $("#" + el);
            var input = el.find("input").eq(0),
                up = el.find(".count-up").eq(0),
                down = el.find(".count-down").eq(0),
                old_value = input.val(); //原始值
            var reg;
            if(el.data("reg")){
                reg = new RegExp(el.data("reg")); //自定义正则
            }else{
                reg = /^-?(0|[1-9]*\d*)(\.\d{1,2})?$/
            }
            var minValue = el.data("min-value") !== undefined ? parseFloat(el.data("min-value")) : undefined;
            var maxValue = el.data("max-value") !== undefined ? parseFloat(el.data("max-value")) : undefined;
            
            // 过滤输入的错误数据
            input.on("blur",function(){
                var new_value = $(this).val();
                if(isNaN(parseFloat(new_value))){
                    $(this).val(old_value);
                    return;
                }
                //匹配格式是否正确
                if(!reg.test(new_value)){
                    $(this).val(old_value);
                }
            });
            up.on("click",function(){
                countNum();
            });
            down.on("click",function(){
                countNum(true);
            });
            // 计算数字加减
            function countNum(IsSub){
                var add_num = IsSub ? -1 : 1;
                var input_val = input.val();
                if(isNaN(parseFloat(input_val))){
                    input_val = "0";
                }
                //递减
                if(typeof minValue !== "undefined" && IsSub && parseFloat(input_val) <= minValue){
                    return;
                }
                if(typeof maxValue !== "undefined" && !IsSub && parseFloat(input_val) >= maxValue){
                    return;
                }
                if(input_val.indexOf(".") > 0){
                    var number_arr = input_val.split(".");
                    var num_0 = Number(number_arr[0]);
                    var count_val = (num_0 + add_num) + "." + number_arr[1];
                    input.val(count_val);
                }else{
                    var add_value = parseInt(input_val,10) + add_num;
                    input.val(add_value);
                }
            }
        },
        /**
         * 检验表单字段的值
         * @param {type} fieldId 字段id
         * @param {type} required 是否必填
         * @param {type} msg 校验不通过的提示信息
         * @returns {Boolean|String} 失败时返回false,成功时返回字段的值。
         */
        checkField:function(fieldId,required, msg) {
            msg = msg || "不能为空";
            var $field = $("#" + fieldId);
            var value = $.trim($field.val());
            var $err = this.getErr(fieldId);
            if (required && value.length == 0) {
                $err.html(msg).removeClass("none");
                return false;
            }
            var maxLength = parseInt($field.attr("maxlength")) || 0;
            if (maxLength && value.length > maxLength) {
                $err.html("超出字符长度限制").removeClass("none");
                return false;
            }
            $err.html("").addClass("none");
            return value;
        },
        checkNumber:function(fieldId,required,msg,reg){
            var $field = $("#" + fieldId);
            var value = $.trim($field.val());
            var $err = this.getErr(fieldId);
            if (required && value.length == 0) {
                $err.html("不能为空").removeClass("none");
                return false;
            }
            var regObj = reg || /^-?(0|[1-9]*\d*)(\.\d{1,2})?$/;
            msg = msg || "格式不正确";
            if(value != "" && regObj.test(value) == false){
                $err.html(msg).removeClass("none");
                return false;
            }
            $err.html("").addClass("none");
            return value;
        },
        /**
         * 校验编辑器的值
         * @param {type} id 编辑器id
         * @param {type} required 是否必填
         * @param {type} msg 校验不通过的提示信息
         * @returns {Boolean|String} 失败时返回false,成功时返回字段的值。
         */
        checkEditor:function(id,required,msg){
            msg = msg || "不能为空";
            var editLib = window['UE'] || window['UM'];
            var editor = editLib.getEditor(id);
            var $err = this.getErr(id);
            if (required && !editor.hasContents()){
                $err.html(msg).removeClass("none");
                return false;
            }
            $err.html("").addClass("none");
            return editor.getContent();
        },
        getErr:function(fieldId){
            var $field = $("#" + fieldId);
            var $err = $field.nextAll(".js-err");
            if($err.length == 0){
                $err = $('<p class="c-red none js-err" style="clear:both;">不能为空</p>').appendTo($field.parent());
            }
            $field = null;
            return $err;
        },
        checkDropDownList:function(id,required,msg){
            msg = msg || "不能为空";
            var $ddl = $("#" + id);
            var value = $ddl.data("value") || "";
            var $err = this.getErr(id);
            if (required && !value){
                $err.html(msg).removeClass("none");
                return false;
            }
            $err.html("").addClass("none");
            return value;
        },
        /**
         * 调用百度地图选择位置
         * @param {function} callBack 回调方法
         * @param {object} data 要传给iframe的初始化位置{longitude:120.640761,latitude:31.259254}
         * @returns {undefined}
         */
        selLocation:function(callBack,data){
            require.async("dialogplus",function(dialog){
                dialog({
                    title:"设置坐标",
                    width:600,
                    height:300,
                    url:"/public/js/plugins/sel_location/sel_location.shtml",
                    data:data,
                    onclose:function(){
                        if(typeof callBack == "function"){
                            callBack.call(this,this.returnValue);
                        }
                    }
                }).showModal();
                top.dialog = dialog; 
            });
        },
        openSwitch:function(id){
            $("#" + id).removeClass("switch-off").addClass("switch-on").find(".switch-text").text("开");
        },
        offSwitch:function(id){
            $("#" + id).removeClass("switch-on").addClass("switch-off").find(".switch-text").text("关");
        }
    };
    module.exports = UI;
});